package com.weiqiao.report.distributior.Service.impl;


import com.google.gson.Gson;

import com.mingsoft.util.StringUtil;
import com.weiqiao.mall.domain.AppUserEntity;
import com.weiqiao.mall.repository.impl.AppUserRepositoryImpl;

import com.weiqiao.order.repository.IOrderRepository;

import com.weiqiao.report.distributior.Service.IOrderReportService;
import com.weiqiao.report.distributior.domain.OrdersReportEntity;
import com.weiqiao.report.distributior.domain.dto.OrdersReportEntityDTO;
import com.weiqiao.report.util.MemberTypeUtil;
import com.weiqiao.utils.DateUtil;
import com.weiqiao.utils.SecurityUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;


import java.text.SimpleDateFormat;
import java.util.*;


@Service("ReportOrderServiceImpl")
public class OrderReportServiceImpl implements IOrderReportService {
    @Autowired
    private IOrderRepository orderRepository;

    @Autowired
    private AppUserRepositoryImpl user;


    @Override
    public List<OrdersReportEntityDTO> getOrderList(OrdersReportEntity vo, Pageable pageable) {
        Integer company_id = SecurityUtils.getCompanyId();
        Document doc = this.getOrderFilter(vo); // 查询条件
        List<String> list = orderRepository.getPage(company_id, doc, pageable);
        List<OrdersReportEntityDTO> result = new ArrayList<>();
        Gson gson = new Gson();

        for (String s : list) {
            OrdersReportEntityDTO order = gson.fromJson(s, OrdersReportEntityDTO.class);
            if (order.getRecommend_id() > 0) {
                // 查询这个用户的绑定上级信息
                String appUser = user.getAppUserByFilter(new Document("user_id", order.getRecommend_id()), company_id);
                if (!StringUtil.isBlank(appUser)) {
                    AppUserEntity userEntity = gson.fromJson(appUser, AppUserEntity.class);
                    order.setRecommend_member_type(userEntity.getMember_type());
                    order.setRecommend_name(userEntity.getNickname());
                }

            }
            result.add(order);
        }
        return result;
    }

    private Document getOrderFilter(OrdersReportEntity vo) {
        Document doc = new Document("order_type", 0);
        if (!StringUtils.isBlank(vo.getKeywords())) {  // 手机号 微信昵称
            List<Document> docList = new ArrayList<>();
            docList.add(new Document("phone", new Document("$regex", vo.getKeywords())));
            docList.add(new Document("nickname", new Document("$regex", vo.getKeywords())));
            doc.append("$or", docList);
        }
        if (!StringUtils.isBlank(vo.getCreate_date())) { // 订单时间
            String time = vo.getCreate_date();
            doc.append("create_date", new Document("$gte", "" + DateUtil.getTime(time.split("~")[0])).append("$lte",
                    "" + DateUtil.getTime(time.split("~")[1])));
        }
        if (!StringUtils.isBlank(vo.getOrder_no())) { //订单ID
            doc.append("order_no", new Document("$regex", vo.getOrder_no()));
        }
        if (!StringUtils.isBlank(vo.getOrder_nos())) {
            String[] strL = vo.getOrder_nos().split(",");  // 接受数组 切割为字符串
            doc.append("order_no", new Document("$in", Arrays.asList(strL)));
        }
        return doc;
    }


    @Override
    public int countNum(OrdersReportEntity vo) {
        Integer company_id = SecurityUtils.getCompanyId();
        Document doc = this.getOrderFilter(vo);
        return orderRepository.countNum(company_id, doc);
    }

    /*
     导出表格
     */
    @Override
    public List<Map<String, Object>> expportOrderList(OrdersReportEntity vo) {
        List<Map<String, Object>> exportContent = new ArrayList<>();
        Document doc = this.getOrderFilter(vo);
        int company_id = vo.getCompany_id();
        List<String> list = orderRepository.getOrderListAndPage(company_id, doc, new Document("create_date", -1), 0, 1000);
        if (CollectionUtils.isNotEmpty(list)) {
            Gson gson = new Gson();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            for (String str : list) {
                OrdersReportEntityDTO entity = gson.fromJson(str, OrdersReportEntityDTO.class);
                if (StringUtil.isLong(entity.getCreate_date())) {
                    entity.setCreate_date(simpleDateFormat.format(Long.parseLong(entity.getCreate_date())));
                }
                // 查询这个用户的绑定上级信息
                if (entity.getRecommend_id() > 0) {
                    String appUser = user.getAppUserByFilter(new Document("user_id", entity.getRecommend_id()), company_id);
                    if (!StringUtil.isBlank(appUser)) {
                        AppUserEntity userEntity = gson.fromJson(appUser, AppUserEntity.class);
                        entity.setRecommend_name(userEntity.getNickname());
                        entity.setRecommend_member_type(userEntity.getMember_type());
                    }
                }
                exportContent.add(createExcelContent(entity));
            }
        }
        return exportContent;
    }

    public Map<String, Object> createExcelContent(OrdersReportEntityDTO order) {
        Map map = new LinkedHashMap();
        map.put("手机号码", order.getPhone());
        map.put("微信昵称", order.getNickname());
        map.put("姓名", order.getUser_name());
        map.put("所属推广员", order.getRecommend_name());
        map.put("推广员等级", MemberTypeUtil.getMemberType(order.getRecommend_member_type()));
        map.put("订单号", order.getOrder_no());
        map.put("自身收益", order.getCommission());
        map.put("上级推广收益", order.getUp_commission());
        map.put("上上级推广收益", order.getSuper_up_commission());
        map.put("订单时间", order.getCreate_date());
        map.put("状态", getOrderType(order.getState()));
        return map;
    }


    /**
     * @param orderType
     * @return
     */
    private String getOrderType(int orderType) {
        String type = "";
        // { 0: '进件', 1: '初审', 2: '核卡', 4: '激活', 8: '首刷', 16: '审核失败', 32: '无数据', 100: '作废' }
        switch (orderType) {
            case 0:
                type = "进件";
                break;
            case 1:
                type = "初审";
                break;
            case 2:
                type = "核卡";
                break;
            case 4:
                type = "激活";
                break;
            case 8:
                type = "首刷";
                break;
            case 16:
                type = "审核失败";
                break;
            case 32:
                type = "无数据";
                break;
            case 100:
                type = "作废";
                break;

        }
        return type;
    }
}
